﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
using System.Data.Linq;
using System.IO.IsolatedStorage;
using Windows.Devices.Geolocation;
using Windows.System;

namespace mobileS.SitesList
{
    public class UserSet
    {
        public int Id { get; set; }

        [JsonProperty(PropertyName = "Email")]
        public string Email { get; set; }

        [JsonProperty(PropertyName = "SocialId")]
        public string SocialId { get; set; }

        [JsonProperty(PropertyName = "Name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "Admin")]
        public bool Admin { get; set; }
    }

    public class SiteSet
    {
        [JsonProperty(PropertyName = "id")]
        public int Id { get; set; }

        [JsonProperty(PropertyName = "Name")]
        public string Name { get; set; }

        //[JsonProperty(PropertyName = "Logo")]
        //public Binary Logo { get; set; }

        [JsonProperty(PropertyName = "Style")]
        public string Style { get; set; }

        [JsonProperty(PropertyName = "GoodType")]
        public string GoodType { get; set; }

        //[JsonProperty(PropertyName = "AdminId")]
        //public string AdminId { get; set; }
    }

    public partial class SitesList : PhoneApplicationPage
    {
        bool islogged = false;
        public SitesList()
        {
            InitializeComponent();
        }

        private async System.Threading.Tasks.Task Authenticate()
        {
            MobileServiceCollection<UserSet, UserSet> usr = null;
            if (!(IsolatedStorageSettings.ApplicationSettings.Contains("UserSocialId") && (!((string)IsolatedStorageSettings.ApplicationSettings["UserSocialId"]).Equals(string.Empty))))
            {
                while ((usr == null) && !islogged)
                {
                    string message = string.Empty;
                    bool registeredOl4Rent = true;
                    try
                    {
                        registeredOl4Rent = true;
                        MobileServiceUser user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook);
                        if (!islogged)
                        {
                            IMobileServiceTable<UserSet> userSetTable = App.MobileService.GetTable<UserSet>();
                            usr = await userSetTable.Where(usrAux => usrAux.SocialId == user.UserId.Split(':')[1]).ToCollectionAsync();
                            if (usr.Count == 0)
                            {
                                usr = null;
                                registeredOl4Rent = false;
                                message = string.Format("Please, register in www.ol4rent.com before using this app!");
                            }
                            else
                            {
                                IsolatedStorageSettings.ApplicationSettings["UserSocialId"] = usr.First().SocialId;
                                message = string.Format("Welcome " + usr.First().Name + "!");
                            }
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        message = "Log in to access this app!";
                    }
                    MessageBox.Show(message);
                    if (!registeredOl4Rent)
                    {
                        await Launcher.LaunchUriAsync(new Uri("http://www.ol4rent.com"));
                    }
                }
                islogged = true;
            }
        }

        private async void LoadSites()
        {
            ListItems.ItemsSource = null;
            loadingText.Visibility = Visibility.Visible;
            loagindBar.Visibility = Visibility.Visible;
            IMobileServiceTable<SiteSet> sitesSetTable = App.MobileService.GetTable<SiteSet>();
            ListItems.ItemsSource = await sitesSetTable.ToCollectionAsync();
            loadingText.Visibility = Visibility.Collapsed;
            loagindBar.Visibility = Visibility.Collapsed;
        }

        private void NavigateToGoodsList(object sender, RoutedEventArgs e)
        {
            int siteId = ((SiteSet)((Button)sender).DataContext).Id;
            NavigationService.Navigate(new Uri("/GoodsList.xaml?siteId=" + siteId, UriKind.Relative));
        }

        # region Location
        async protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //await Authenticate();

            if (!(IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent") && ((bool) IsolatedStorageSettings.ApplicationSettings["LocationConsent"])))
            {
                MessageBoxResult result = MessageBox.Show("This app will use the location of your phone. Is that ok?", "Location", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
                }
                else
                {
                    IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
                }

                IsolatedStorageSettings.ApplicationSettings.Save();
            }

            FindLoaction();
            LoadSites();
        }

        private async void FindLoaction()
        {
            IsolatedStorageSettings.ApplicationSettings["LocationLatitude"] = null;
            IsolatedStorageSettings.ApplicationSettings["LocationLongitude"] = null;
            if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] == true)
            {
                Geolocator geolocator = new Geolocator();
                geolocator.DesiredAccuracyInMeters = 50;

                try
                {
                    Geoposition geoposition = await geolocator.GetGeopositionAsync(maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10));

                    IsolatedStorageSettings.ApplicationSettings["LocationLatitude"] = geoposition.Coordinate.Latitude.ToString("0.00");
                    IsolatedStorageSettings.ApplicationSettings["LocationLongitude"] = geoposition.Coordinate.Longitude.ToString("0.00");
                }
                catch (Exception ex)
                {
                    if ((uint)ex.HResult == 0x80004004)
                    {
                        MessageBox.Show("Location is disabled, you should activate it in order to improve the searchs.", "Location", MessageBoxButton.OK);
                        // the application does not have the right capability or the location master switch is off
                        //StatusTextBlock.Text = "location  is disabled in phone settings.";
                    }
                    else
                    {
                        MessageBox.Show("Error al calcular la ubicación.", "Ubicación", MessageBoxButton.OK);
                    }
                    IsolatedStorageSettings.ApplicationSettings["LocationLatitude"] = null;
                    IsolatedStorageSettings.ApplicationSettings["LocationLongitude"] = null;
                }
            }
        }

        #endregion
    }
}